#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
#define MINBUFSZ 512		/* minimum buffer size: must be > 0 */
static char *lhbuf = NULL;
static int lhbufsz = 0;

int max(int a,int b)
{
  return (a>b)?a:b;
}

int mutex = 0;			/* if set, signals set "sigflags" */
int sigflags = 0;		/* if set, signals received while mutex set */
char *errmsg;
void handle_hup (int signo)
{
  printf("signo = %d\n",signo);
}
void handle_int(int signo)
{
  printf("signo = %d\n",signo);
  exit(1);
}

void SPL0() 
{
  if (--mutex == 0)							
    {								
      if (sigflags & (1 << (SIGHUP - 1))) handle_hup (SIGHUP);	
      if (sigflags & (1 << (SIGINT - 1))) handle_int (SIGINT);	
    }
}

int SPL1()
{
 return mutex++;
}

int realloc1(char *b, int n, int i,int err)
{
  if (i > n)							
    {								
      int ti = n;							
      char *ts;							
      SPL1 ();							
      if (b != NULL)						
        {								
          if ((ts = (char *) realloc ((b), ti += max ((i), MINBUFSZ))== NULL))
            {
              fprintf (stderr, "%s\n", strerror (errno));		
              //              sprintf (errmsg, "Out of memory");
              SPL0 ();						
              return err;						
            }							
        }								
      else								
        {								
          if ((ts = (char *) malloc (ti += max ((i), MINBUFSZ))) == NULL)
            {
              fprintf (stderr, "%s\n", strerror (errno));		
              sprintf (errmsg, "Out of memory");			
              SPL0 ();						
              return err;						
            }							
        }								
      lhbufsz = ti;							
      lhbuf = ts;							
      SPL0 ();							
    }
  return 0;
}



int main(int argc, char *argv[])
{
  static char *ibufp = "[0-9]abcdefasdfasdf\r\n";
  int len = strlen(ibufp);
  realloc1(lhbuf,lhbufsz,len + 1,NULL);
  memcpy(lhbuf,ibufp,len);
  lhbuf[len] = '\0';
  printf("%s\n",lhbuf);
  
  return 0;
}
